<?php


namespace app\user\controller;


use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Invoice extends Base
{
    protected $search_condition;
    protected $search_result;
    protected $search_rate;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->search_condition = [
            ['name'=>'发票代码','value'=>1,'checked'=>true],
            ['name'=>'原发票代码','value'=>5,'checked'=>true],
            ['name'=>'发票号码','value'=>2,'checked'=>true],
            ['name'=>'原发票号码','value'=>6,'checked'=>true],
            ['name'=>'客户名称','value'=>3,'checked'=>true],
            ['name'=>'开票人','value'=>4,'checked'=>true],
            ['name'=>'作废人','value'=>7,'checked'=>true],
        ];

        $this->search_result = [
            ['name'=>'发票类型','checked'=>true,'id'=>23,'item'=>'bill','width'=>'135'],
            ['name'=>'发票状态','checked'=>true,'id'=>24,'item'=>'tax_type','width'=>'100'],
            ['name'=>'发票代码','checked'=>true,'id'=>25,'item'=>'kp_code','width'=>'120'],
            ['name'=>'发票号码','checked'=>true,'id'=>26,'item'=>'kp_no','width'=>'100'],
            ['name'=>'上传状态','checked'=>true,'id'=>27,'item'=>'status','width'=>'100'],
            ['name'=>'开票日期','checked'=>true,'id'=>35,'item'=>'kp_time','width'=>'150'],
            ['name'=>'税额','checked'=>true,'id'=>28,'item'=>'content_tax','width'=>'150'],
            ['name'=>'合计金额','checked'=>true,'id'=>29,'item'=>'content_money','width'=>'150'],
            ['name'=>'价税合计','checked'=>true,'id'=>30,'item'=>'content_sum','width'=>'200'],
            ['name'=>'购方纳税人名称','checked'=>true,'id'=>40,'item'=>'buy_name','width'=>'300'],
            ['name'=>'原发票代码','checked'=>true,'id'=>31,'item'=>'no_1','width'=>'100'],
            ['name'=>'原发票号码','checked'=>true,'id'=>32,'item'=>'no_2','width'=>'100'],
            ['name'=>'通知单编号','checked'=>true,'id'=>33,'item'=>'no_3','width'=>'150'],
            ['name'=>'开票人','checked'=>true,'id'=>34,'item'=>'drawer','width'=>'100'],
            ['name'=>'作废人','checked'=>true,'id'=>36,'item'=>'no_4','width'=>'100'],
            ['name'=>'作废日期','checked'=>true,'id'=>37,'item'=>'no_5','width'=>'100'],
            ['name'=>'客户识别号','checked'=>true,'id'=>38,'item'=>'buy_num','width'=>'200'],
            ['name'=>'清单标识','checked'=>true,'id'=>39,'item'=>'no_7','width'=>'100'],
        ];

        $this->search_rate = [
            ['field'=>'rate_6','text'=>'6%','value'=>0.06],
            ['field'=>'rate_17','text'=>'17%','value'=>0.17],
            ['field'=>'rate_16','text'=>'16%','value'=>0.16],
            ['field'=>'rate_13','text'=>'13%','value'=>0.13],
            ['field'=>'rate_11','text'=>'11%','value'=>0.11],
            ['field'=>'rate_10','text'=>'10%','value'=>0.10],
            ['field'=>'rate_9','text'=>'9%','value'=>0.09],
            ['field'=>'rate_5','text'=>'5%','value'=>0.05],
            ['field'=>'rate_4','text'=>'4%','value'=>0.04],
            ['field'=>'rate_3','text'=>'3%','value'=>0.03],
        ];
    }

    public function getRateByField($field){
        $index = array_search($field,array_column($this->search_rate,'field'));
        return $this->search_rate[$index];
    }

    public function csSetting(){
    return $this->fetch('csSetting');
    }

    public function SetSearch(){
        if (IsPost()){
            $Data = Param();
            $arr1 = $this->search_condition;
            $temp1 = [];$temp2 = [];
            foreach ($Data['condition'] as $k=>$v){
                foreach ($arr1 as $kk=>$vv){
                    if ($v['value'] == $vv['value']){
                        $arr1[$kk]['checked'] = $v['checked'];
                        if ($v['checked']){
                            array_push($temp1,$vv['value']);
                        }
                    }
                }
            }
            if (count($temp1) <= 0){
                return ['status'=>0,'message'=>'至少保留一个'];
            }
            Session::set('search_condition',$arr1);
            $arr2 = $this->search_result;
            foreach ($Data['result'] as $k=>$v){
                foreach ($arr2 as $kk=>$vv){
                    if ($v['value'] == $vv['item']){
                        $arr2[$kk]['checked'] = $v['checked'];
                        if ($v['checked']){
                            array_push($temp2,$vv['value']);
                        }
                    }
                }
            }
            if (count($temp2) <= 0){
                return ['status'=>0,'message'=>'至少保留一项'];
            }
            Session::set('search_result',$arr2);
            return ['status'=>1,'message'=>'成功','data'=>['condition'=>$arr1,'result'=>$arr2]];
        }
    }
    /**
     * Notes:已开发票查询
     * User: ming
     * Date: 2022/1/22
     * Time: 15:59
     * @return mixed
     */
    public function Invoicingsystem(){
        Session::delete('search_condition');
        Session::delete('search_result');
        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'bill'=>'1',
                'status_tax'=>'',
                'search_type'=>'1',
                'search_name'=>'',
                'create_time' => ''
            ];
            $is_search = 0;
        }else{
            $is_search = 1;
        }
        $arr = explode(',',$Data['status_tax']);
        $this->assign('arr',$arr);
        $this->assign('Data',$Data);
        $search_condition = Session::get('search_condition') ? Session::get('search_condition'):$this->search_condition;
        $search_result = Session::get('search_result') ? Session::get('search_result'):$this->search_result;
        $monthBegin = date('Y-m-01');
        $monthEnd = date('Y-m-d');
        $this->assign([
            'search_condition'=>$search_condition,
            'search_result'=>$search_result,
            'search_result_json'=>json_encode($search_result,JSON_UNESCAPED_UNICODE),
            'monthBegin'=>$monthBegin,
            'monthEnd'=>$monthEnd,
        ]);
        $Where = [];
        if($Data['bill'] != ''){
            $Where['bill'] = $Data['bill'];
        }
        if($Data['search_type'] != '' && $Data['search_name'] != ''){
            if($Data['search_type'] == 1){
                //发票代码
                $Where['kp_code'] = ['like','%'.$Data['search_name'].'%'];
            }elseif ($Data['search_type'] == 2) {
                // 发票号码
                $Where['kp_no'] = ['like','%'.$Data['search_name'].'%'];
            }elseif ($Data['search_type'] == 3) {
                // 纳税人
                $Where['buy_name'] = ['like','%'.$Data['search_name'].'%'];
            }elseif ($Data['search_type'] == 4) {
                // 开票人
                $Where['payee'] = ['like','%'.$Data['search_name'].'%'];
            }
        }
        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
           $BeginTime = strtotime($Data['begin_time']);
           $Where['kp_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['kp_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['kp_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }
        if ($is_search == 1){
            //总记录条数
            $Count = InvoiceCount($Where);
            $this->assign('Count',$Count);

            //列表
            $InvoiceList = InvoiceList($Where);
            $this->assign('InvoiceList',$InvoiceList['InvoiceList']);

            //分页
            $this->assign('Page', $InvoiceList['Page']);

            //统计数据
            $total = Db::name('invoice')->where($Where)->field('sum(content_tax) tax,sum(content_money) money')->find();
//        $all['tax'] = array_sum(array_column($total,'content_tax'));
//        $all['money'] = array_sum(array_column($total,'content_money'));
            $all['tax'] = $total['tax'];$all['money'] = $total['money'];
            $all['tax_money'] = $all['tax'] + $all['money'];

            $current['tax'] = array_sum(array_column($InvoiceList['InvoiceList'],'content_tax'));
            $current['money'] = array_sum(array_column($InvoiceList['InvoiceList'],'content_money'));
            $current['tax_money'] = $current['tax'] + $current['money'];
            $this->assign('all',$all);
            $this->assign('current',$current);
        }else{
            $this->assign('Count',0);
            $this->assign('InvoiceList',[]);
            $this->assign('Page','');
            $this->assign('all',[]);
            $this->assign('current',[]);
        }

        //配置参数
        $this->assign('bill_type',\think\Config::get('bill_type'));
        $this->assign('search_type',\think\Config::get('search_type'));
        $this->assign('today','');
        return $this->fetch('Invoicingsystem');
    }
     public function settings(){
        return $this->fetch('settings');
    }
      public function bill2(){
        return $this->fetch('bill_2');
    }

    public function InvoicingsystemAjax(){
        if ($this->request->isAjax()){
            $params = array_merge([
                'bill'=>'1',
                'status_tax'=>'',
                'search_type'=>'1',
                'search_name'=>'',
                'begin_time' => '',
                'end_time'=>'',
                'limit'=>10
            ],$this->request->param());

            $Where = [];
            if($params['bill'] != ''){
                $Where['bill'] = $params['bill'];
            }
            if($params['search_type'] != '' && $params['search_name'] != ''){
                if($params['search_type'] == 1){
                    //发票代码
                    $Where['kp_code'] = ['like','%'.$params['search_name'].'%'];
                }elseif ($params['search_type'] == 2) {
                    // 发票号码
                    $Where['kp_no'] = ['like','%'.$params['search_name'].'%'];
                }elseif ($params['search_type'] == 3) {
                    // 纳税人
                    $Where['buy_name'] = ['like','%'.$params['search_name'].'%'];
                }elseif ($params['search_type'] == 4) {
                    // 开票人
                    $Where['payee'] = ['like','%'.$params['search_name'].'%'];
                }
            }
            //时间查询
            if($params['begin_time'] != '' && $params['end_time'] == ''){   //只有开始时间没有结束时间
                $BeginTime = strtotime($params['begin_time']);
                $Where['kp_time'] = array('egt',$BeginTime );
            }

            if($params['begin_time'] == '' && $params['end_time'] != ''){   //只有结束时间没有开始时间
                $EndTime = strtotime($params['end_time']);
                $Where['kp_time'] = array('elt',$EndTime );
            }

            if($params['begin_time'] != '' && $params['end_time'] != ''){   //有开始时间有结束时间
                $BeginTime = strtotime($params['begin_time']);
                $EndTime = strtotime($params['end_time']);
                $Where['kp_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
            }
            $config = [1=>'增值税专用发票',2=>'增值税普通发票',3=>'增值税电子专用发票',4=>'增值税电子普通发票'];
            $config2 = [1=>'正数发票',2=>'正数废票',3=>'负数发票',4=>'负数废票'];
            $list = Db::name('invoice')->where($Where)->order('kp_time desc,id desc')->paginate($params['limit'])->each(function ($item)use ($config,$config2){
                $item['bill'] = $config[$item['bill']];
                $item['tax_type'] = $config2[$item['tax_type']];
                $item['status'] = $item['status'] == 1 ? '已上传':'未上传';
                $item['content_sum'] = bcadd($item['content_money'],$item['content_tax'],2);
                $item['kp_time'] = date('Y-m-d',$item['kp_time']);
                return $item;
            })->toArray();

            $current['money'] = number_format(array_sum(array_column($list['data'],'content_money')),2,'.','');
            $current['tax'] = number_format(array_sum(array_column($list['data'],'content_tax')),2,'.','');
            $current['total'] = bcadd($current['money'],$current['tax'],2);

            $all = Db::name('invoice')->where($Where)->field('sum(content_tax) tax,sum(content_money) money')->find();
            $total['money'] = $all['money'];
            $total['tax'] = $all['tax'];
            $total['total'] = bcadd($total['money'],$total['tax'],2);

            $result['current'] = $current;
            $result['total'] = $total;
            $result['list'] = $list;
            return ['status'=>1,'message'=>'','data'=>$result];
        }


    }
    
    //查看原票
    public function Invoiced(){
        $id = Param('id');
        // $id = 11;
        $info = Db::name('invoice')->where(['id'=>$id])->find();
        $this->assign('info',$info);
        $pas = md5($info['kp_machine_code']).'+'. md5($info['kp_code']).'*/*'.md5($info['kp_no']).'-+'.md5($info['kp_machine_code'].$info['kp_code']);
        $this->assign('pas',$pas);
        // $all = floor($info['content_money'] + $info['content_tax']);
        $all = number_format($info['content_money'] + $info['content_tax'],2,'.','');
        $this->assign('all',$all);
        // $money = $this->convertAmountToCn($info['content_money'] + $info['content_tax']);
        $money = $this->convertAmountToCn($all);
        $this->assign('money',$money);
        
        return $this->fetch('Invoiced');
    }
    
    
     public function convertAmountToCn($amount, $type = 1) {
        // 判断输出的金额是否为数字或数字字符串
        if(!is_numeric($amount)){
            return "要转换的金额只能为数字!";
        }

        // 金额为0,则直接输出"零元整"
        if($amount == 0) {
            return "零元整";
        }

        // 金额不能为负数
        if($amount < 0) {
            return "要转换的金额不能为负数!";
        }

        // 金额不能超过万亿,即12位
        if(strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }

        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');

        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);

        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);

        // 将整数部分替换成大写汉字
        $result = '';//前缀
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        for($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if($integerArr[$i] != 0){
                $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            }else{
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }

        // 如果小数位也要转换
        if($type == 0) {
            // 将小数位的数值字符串拆分成数组
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if($decimalArr[0] != 0){
                $result = $result . $digital[$decimalArr[0]] . '角';
            }
            // 将分替换成大写汉字. 如果为0,则不替换
            if($decimalArr[1] != 0){
                $result = $result . $digital[$decimalArr[1]] . '分';
            }
        }else{
            $result = $result . '整';
        }
        return $result;
    }
    public  function kpindex1(){
        $this->assign('today',date('Y-m-d'));
        $this->assign('rate',$this->search_rate);
        return $this->fetch();
    }
    /**
     * Notes:增值税专用发票
     * User: ming
     * Date: 2022/1/22
     * Time: 16:14
     * @return mixed
     */
    public  function kpindex(){
        if(IsPost()){
            $Data = Param();
            if($Data['kp_code'] == ''){
                return ['status'=>0,'message'=>'请输入开票代码'];
            }
            if($Data['kp_no'] == ''){
                return ['status'=>0,'message'=>'请输入开票号码'];
            }
            if ($Data['buy_num'] == ''||$Data['buy_address'] == ''||$Data['buy_name'] == ''||$Data['buy_bank'] == ''){
                return ['status'=>0,'message'=>'请输入购买方信息'];
            }
            if ($Data['content_name'] == '' || $Data['content_rate'] == ''|| $Data['price_tax'] == ''){
                return ['status'=>0,'message'=>'请输开票信息'];
            }
            if ($Data['price_tax'] <= 0 || !is_numeric($Data['price_tax'])){
                return ['status'=>0,'message'=>'请输入价税'];
            }
            $Data['content_money'] = bcdiv($Data['price_tax'],(1 + $Data['content_rate']),2); //货物金额
            $Data['content_tax'] = bcsub($Data['price_tax'],$Data['content_money'],2); //税额
//            if ($Data['content_name'] == ''|| $Data['content_money'] == ''|| $Data['content_rate'] == ''|| $Data['content_tax'] == ''){
//                return ['status'=>0,'message'=>'请输开票信息'];
//            }
//            $Data['content_tax'] = bcmul($Data['content_money'],$Data['content_rate'],2); //税额
            $Data['kp_machine_code'] = '917105087784';
            $Data['kp_title'] = '增值税专用发票';
            $Data['seller_name'] = '华屹（深圳）网络科技服务有限公司';
            $Data['seller_num'] = '91440300305875529Q';
            // $Data['seller_addresss'] = '深圳市南山区西丽街道松坪山社区高新北六道27号 兰光科技大楼A';
            $Data['seller_bank'] = '平安银行深圳坂田支行 15977969180098';

            $Data['create_time']=time();
            $Data['kp_time']=strtotime($Data['kp_time']);
            if ($Data['kp_time'] < 1680278400){
                //2023 04 01 前
                $Data['seller_addresss'] = '深圳市南山区西丽街道松坪山社区高新北六道27号兰光科技大楼A511075';
            }else{
                //后
                $Data['seller_addresss'] = '深圳市龙岗区坂田街道象角塘社区坂田汇智谷创新产业园1栋四层401-405号';
            }
            // $Data['kp_time']=strtotime(date('Y-m-d'));
//            dump($Data);die;
            if ($user_id = Db::name('invoice')->insertGetId($Data)){

                return ['status' => 1, 'message' => '发票开具成功','url'=>url('invoice/kpindex')];
            }else{
                return ['status' => 0, 'message' => '发票开具失败'];
            }
        }
        $this->assign('today',date('Y-m-d'));
        $this->assign('rate',$this->search_rate);
        return $this->fetch('kpindex');
    }
    /**
     * Notes:发票管理
     * User: ming
     * Date: 2022/1/22
     * Time: 16:17
     */
    public function manage(){
        return $this->fetch('manage');
    }



    /**
     * Notes:数据管理
     * User: ming
     * Date: 2022/1/22
     * Time: 16:17
     */
    public function data(){
        return $this->fetch('data');
    }

    /**
     * Notes:发票资料统计
     * User: ming
     * Date: 2022/1/22
     * Time: 16:28
     * @return mixed
     */
    public function search(){
//条件查询
        $Data = Param();
        // dump($Data);die;
        if (empty($Data)){
            $Data = [
                'bill'=>1,
                'create_time' => '',
            ];
        }
        $start = '2021';
        $year = date('Y');
        $month = date('n');
        $yearArr = [];
        for ($i=$start;$i<=$year;$i++){
            array_push($yearArr,$i);
        }
        $Data['month'] = $month;
        $this->assign('Data',$Data);
        $this->assign(compact('year','month','yearArr'));
//        $Where = [];
        // $Where['bill'] = 1;

        if($Data['bill'] != ''){
            $Where['bill'] = $Data['bill'];
        }
        if($Data['year']!=''){
            $timeStart=strtotime($Data['year'].'0101');
             $timeEnd=strtotime($Data['year'].'1231');
            //  $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
            $Where['kp_time'] = ['between',[$timeStart,$timeEnd]];
        }
        //jidu
        if($Data['tj']=="2"){
            if($Data['year']==""){
                return ['status'=>0,'message'=>'请输入哪一年'];
            }
            if($Data['quarter']=="1"){
                $timeStart=strtotime($Data['year'].'0101');
                $timeEnd=strtotime($Data['year'].'0401');
            }
           if($Data['quarter']=="2"){
                $timeStart=strtotime($Data['year'].'0401');
             $timeEnd=strtotime($Data['year'].'0701');
            }
            if($Data['quarter']=="3"){
                $timeStart=strtotime($Data['year'].'0701');
             $timeEnd=strtotime($Data['year'].'10010');
            }
            if($Data['quarter']=="4"){
                $timeStart=strtotime($Data['year'].'1001');
             $timeEnd=strtotime($Data['year'].'0101');
            }
            $Where['kp_time'] = ['between',[$timeStart,$timeEnd]];
        }
        //yue
         if($Data['tj']=="3"){
             $str = str_pad($Data['month'],2,'0',STR_PAD_LEFT);
             $timeStart=strtotime($Data['year'].$str.'01');
            //  $timeEnd=strtotime($Data['year'].$str.'31');
             $timeEnd = strtotime(date('Y-m-t', $timeStart));
            //  $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
            $Where['kp_time'] = ['between',[$timeStart,$timeEnd]];
         }
        //  dump($Data);
        //  dump($Where);die;
        $arr['tax_type1']= Db::name('invoice')->where($Where)->where(['tax_type'=>1])->count();
        $arr['tax_type2']= Db::name('invoice')->where($Where)->where(['tax_type'=>2])->count();
        $arr['tax_type3']= Db::name('invoice')->where($Where)->where(['tax_type'=>3])->count();
        $arr['tax_type4']= Db::name('invoice')->where($Where)->where(['tax_type'=>4])->count();
//        dump($Where);
        $arr['tax_type']= Db::name('invoice')->where($Where)->count('id');
//        dump($arr['tax_type']);die;
        $list=Db::name('invoice')
            ->where($Where)
            ->group('tax_type,content_rate')
            ->field('sum(content_money) AS money ,sum(content_tax) as tax,tax_type,content_rate')
            ->select();
//        dump($list);die;
       if(!empty($list)){
           $val=[];
           foreach ($list as $v){
               if($v['tax_type']==1){
                   $val['tax1']['money_count']+=$v['money'];//金额合计
                   $val['tax1']['tax_count']+=$v['tax'];//税额合计
                   if($v['content_rate'] == 0.16){
                       $val['tax1']['money']['type1'] = $v['money'];
                       $val['tax1']['tax']['type1'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.13){
                        $val['tax1']['money']['type2'] = $v['money'];
                        $val['tax1']['tax']['type2'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.10){
                        $val['tax1']['money']['type3'] = $v['money'];
                        $val['tax1']['tax']['type3'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.09){
                        $val['tax1']['money']['type4'] = $v['money'];
                        $val['tax1']['tax']['type4'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.01){
                        $val['tax1']['money']['type5'] = $v['money'];
                        $val['tax1']['tax']['type5'] = $v['tax'];
                   }else{
                        $val['tax1']['money']['other'] = $v['money'];
                        $val['tax1']['tax']['other'] = $v['tax'];
                   }
                   $val['tax1']['money'][]=$v['money'];
                   $val['tax1']['tax'][]=$v['tax'];
               }
               if($v['tax_type']==2){
                   $val['tax2']['money_count']+=$v['money'];//金额合计
                   $val['tax2']['tax_count']+=$v['tax'];//税额合计
                   if($v['content_rate'] == 0.16){
                       $val['tax2']['money']['type1'] = $v['money'];
                       $val['tax2']['tax']['type1'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.13){
                        $val['tax2']['money']['type2'] = $v['money'];
                        $val['tax2']['tax']['type2'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.10){
                        $val['tax2']['money']['type3'] = $v['money'];
                        $val['tax2']['tax']['type3'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.09){
                        $val['tax2']['money']['type4'] = $v['money'];
                        $val['tax2']['tax']['type4'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.01){
                        $val['tax2']['money']['type5'] = $v['money'];
                        $val['tax2']['tax']['type5'] = $v['tax'];
                   }else{
                        $val['tax2']['money']['other'] = $v['money'];
                        $val['tax2']['tax']['other'] = $v['tax'];
                   }
                   $val['tax2']['money'][]=$v['money'];
                   $val['tax2']['tax'][]=$v['tax'];
               }
               if($v['tax_type']==3){
                   $val['tax3']['money_count']+=$v['money'];//金额合计
                   $val['tax3']['tax_count']+=$v['tax'];//税额合计
                   if($v['content_rate'] == 0.106){
                       $val['tax3']['money']['type1'] = $v['money'];
                       $val['tax3']['tax']['type1'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.13){
                        $val['tax3']['money']['type2'] = $v['money'];
                        $val['tax3']['tax']['type2'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.10){
                        $val['tax3']['money']['type3'] = $v['money'];
                        $val['tax3']['tax']['type3'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.09){
                        $val['tax3']['money']['type4'] = $v['money'];
                        $val['tax3']['tax']['type4'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.01){
                        $val['tax3']['money']['type5'] = $v['money'];
                        $val['tax3']['tax']['type5'] = $v['tax'];
                   }else{
                        $val['tax3']['money']['other'] = $v['money'];
                        $val['tax3']['tax']['other'] = $v['tax'];
                   }
                   $val['tax3']['money'][]=$v['money'];
                   $val['tax3']['tax'][]=$v['tax'];
               }
               if($v['tax_type']==4){
                   $val['tax4']['money_count']+=$v['money'];//金额合计
                   $val['tax4']['tax_count']+=$v['tax'];//税额合计
                   if($v['content_rate'] == 0.16){
                       $val['tax4']['money']['type1'] = $v['money'];
                       $val['tax4']['tax']['type1'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.13){
                        $val['tax4']['money']['type2'] = $v['money'];
                        $val['tax4']['tax']['type2'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.10){
                        $val['tax4']['money']['type3'] = $v['money'];
                        $val['tax4']['tax']['type3'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.09){
                        $val['tax4']['money']['type4'] = $v['money'];
                        $val['tax4']['tax']['type4'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.01){
                        $val['tax4']['money']['type5'] = $v['money'];
                        $val['tax4']['tax']['type5'] = $v['tax'];
                   }else{
                        $val['tax4']['money']['other'] = $v['money'];
                        $val['tax4']['tax']['other'] = $v['tax'];
                   }
                   $val['tax4']['money'][]=$v['money'];
                   $val['tax4']['tax'][]=$v['tax'];
               }
               $val['tax']['money_count']+=$v['money'];//金额合计
               $val['tax']['tax_count']+=$v['tax'];//税额合计
               if($v['content_rate'] == 0.16){
                       $val['tax']['money']['type1'] = $v['money'];
                       $val['tax']['tax']['type1'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.13){
                        $val['tax']['money']['type2'] = $v['money'];
                        $val['tax']['tax']['type2'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.10){
                        $val['tax']['money']['type3'] = $v['money'];
                        $val['tax']['tax']['type3'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.09){
                        $val['tax']['money']['type4'] = $v['money'];
                        $val['tax']['tax']['type4'] = $v['tax'];
                   }elseif($v['content_rate'] == 0.01){
                        $val['tax']['money']['type5'] = $v['money'];
                        $val['tax']['tax']['type5'] = $v['tax'];
                   }else{
                        $val['tax']['money']['other'] = $v['money'];
                        $val['tax']['tax']['other'] = $v['tax'];
                   }
               $val['tax']['money'][]=$v['money'];
               $val['tax']['tax'][]=$v['tax'];
           }
       }
//       dump($val);die;
        $this->assign('val',$val);
        $this->assign('arr',$arr);
        $this->assign('list',$list);
        $this->assign('rate',$this->search_rate);
        return $this->fetch('search');
    }

    /**
     * @title 搜索ajax
     * @author Qian
     * Time: 2023/12/20  10:09
     */
    public function searchAjax(){
        if ($this->request->isGet()){
            $data = \request()->param();
            $params = array_merge([
                'bill'=>1,
                'year'=>'',
                'tj'=>'',
                'month'=>'',
                'create_time' => '',
                'cols'=>['rate_16','rate_13','rate_10','rate_6']
            ],$data);

            $filter = [];
            if ($params['bill'] != ''){
                $filter['bill'] = $params['bill'];
            }
            if($params['year'] != ''){
                $timeStart=strtotime(date("{$params['year']}-01-01"));
                $timeEnd = strtotime(date("{$params['year']}-12-31")) + 86399;
                $filter['kp_time'] = ['between',[$timeStart,$timeEnd]];
            }
            //季度
            if($params['tj']=="2"){
                if($params['year']==""){
                    return ['status'=>0,'message'=>'请输入哪一年'];
                }
                if($params['quarter']=="1"){
                    $timeStart = strtotime($params['year'].'0101');
                    $timeEnd=strtotime($params['year'].'0401') + 86399;
                }elseif($params['quarter']=="2"){
                    $timeStart=strtotime($params['year'].'0401');
                    $timeEnd=strtotime($params['year'].'0701') + 86399;
                }
                elseif($params['quarter']=="3"){
                    $timeStart=strtotime($params['year'].'0701');
                    $timeEnd=strtotime($params['year'].'1001') + 86399;
                }
                elseif($params['quarter']=="4"){
                    $timeStart=strtotime($params['year'].'1001');
                    $timeEnd=strtotime($params['year'].'1231') + 86399;
                }
                $filter['kp_time'] = ['between',[$timeStart,$timeEnd]];
            }
            //月
            if($params['tj']=="3"){
                $str = str_pad($params['month'],2,'0',STR_PAD_LEFT);
                $timeStart=strtotime($params['year'].$str.'01');
                $timeEnd = strtotime(date('Y-m-t', $timeStart)) + 86399;
                $filter['kp_time'] = ['between',[$timeStart,$timeEnd]];
            }
            $total['tax_type1']= Db::name('invoice')->where($filter)->where(['tax_type'=>1])->count();
            $total['tax_type2']= Db::name('invoice')->where($filter)->where(['tax_type'=>2])->count();
            $total['tax_type3']= Db::name('invoice')->where($filter)->where(['tax_type'=>3])->count();
            $total['tax_type4']= Db::name('invoice')->where($filter)->where(['tax_type'=>4])->count();
            $total['tax'] = Db::name('invoice')->where($filter)->count('id');
            $list=Db::name('invoice')
                ->where($filter)
                ->group('tax_type,content_rate')
                ->field('sum(content_money) AS money ,sum(content_tax) as tax,tax_type,content_rate')
                ->select();
            $val=[];
            if(!empty($list)){
                $config = [
                    ['title'=>'销项正数','tax_type'=>1],
                    ['title'=>'销项正废','tax_type'=>2],
                    ['title'=>'销项负数','tax_type'=>3],
                    ['title'=>'销项负废','tax_type'=>4],
                ];
                $table_total_money= 0;
                $table_total_tax = 0;
                $table_col_money = [];
                $table_col_tax = [];
                foreach($config as $ck=>$cv){
                    $cv_total_money = 0;
                    $cv_total_tax = 0;
                    $cols_money = [];
                    $cols_tax = [];
                    //初始化
                    foreach ($params['cols'] as $kk=>$vv) {
                        $cols_money[$vv] = number_format(0,2);
                        $cols_tax[$vv] = number_format(0,2);;
                    }
                    foreach ($list as $k=>$v){
                        if($v['tax_type'] == $cv['tax_type']){
                            $cv_total_money = bcadd($cv_total_money,$v['money'],2);
                            $cv_total_tax = bcadd($cv_total_tax,$v['tax'],2);
                            foreach ($params['cols'] as $kk=>$vv){
                                $field  = $this->getRateByField($vv);
                                if ($v['content_rate'] == $field['value']){
                                    $cols_money[$vv] = $v['money'];
                                    $cols_tax[$vv] = $v['tax'];
                                }
                            }
                        }
                    }
                    $val[] = array_merge([
                        'title'=>$cv['title']."金额",
                        'total'=>$cv_total_money,
                        'other'=>bcsub($cv_total_money,array_sum(array_values($cols_money)),2),
                    ],$cols_money);
                    $val[] = array_merge([
                        'title'=>$cv['title']."税额",
                        'total'=>$cv_total_tax,
                        'other'=>bcsub($cv_total_tax,array_sum(array_values($cols_tax)),2),
                    ],$cols_tax);
                    //总
                    foreach ($params['cols'] as $kk=>$vv){
                        $table_col_money[$vv] = bcadd($table_col_money[$vv],$cols_money[$vv],2);
                        $table_col_tax[$vv] = bcadd($table_col_tax[$vv],$cols_tax[$vv],2);
                    }
                    $table_total_money = bcadd($table_total_money,$cv_total_money,2);
                    $table_total_tax = bcadd($table_total_tax,$cv_total_tax,2);
                }
                //最后两行统计
                $val[] = array_merge([
                    'title'=>'实际销售金额',
                    'total'=>$table_total_money,
                    'other'=>bcsub($table_total_money,array_sum(array_values($table_col_money)),2),
                ],$table_col_money);
                $val[] = array_merge([
                    'title'=>'实际销售税额',
                    'total'=>$table_total_tax,
                    'other'=>bcsub($table_total_tax,array_sum(array_values($table_col_tax)),2),
                ],$table_col_tax);
            }
            return ['status'=>1,'message'=>'','data'=>['list'=>$val,'total'=>$total,'search_rate'=>array_column($this->search_rate,null,'field')]];
        }
    }
    /**
     * Notes:系统设置
     * User: ming
     * Date: 2022/1/22
     * Time: 16:33
     * @return mixed
     */
    public function set(){
    return $this->fetch('set');
}
    /**
     * Notes:系统维护
     * User: ming
     * Date: 2022/1/22
     * Time: 16:33
     * @return mixed
     */
    public function maintain(){
        return $this->fetch('maintain');
    }
    public function Index(){
//        //轮播
//        $banner = Db::name('banner')->select();
        //简介
        $Config = Config();
        //记录
        $record = Db::name('user_deposit')->where(['user_id'=>$this->user_id])->select();

        //最新公告
        $notice = Db::name('notice')->order('id desc')->limit(4)->select();
        //累计静态
        $reward1 = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>13])->sum('num');
        //累计动态
        $reward2 = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>14])->sum('num');
        //累计手数佣金
        $reward3 = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>15])->sum('num');
        //团队动态手数
        $reward4 = Db::name('finance')->where(['user_id'=>$this->user_id,'reward_type'=>16])->sum('num');
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        $withdraw = Db::name('user_withdraw')->where(['user_id'=>$this->user_id,'status'=>1])->sum('num');
        $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);

        $this->assign([
//            'banner'=>$banner,
            'record'=>$record,
            'config'=>$Config,
            'notice'=>$notice,
            'reward1'=>$reward1,
            'reward2'=>$reward2,
            'reward3'=>$reward3,
            'reward4'=>$reward4,
            'UserInfo'=>$UserInfo,
            'withdraw'=>$withdraw,
            'LevelInfo'=>$LevelInfo,
        ]);
        return $this->fetch('Index');
    }

    public function Index2(){
        $Config = Config();
        $this->assign([
            'config'=>$Config,
        ]);
        return $this->fetch('Index3');
    }

    public function getMore(){
        $page = Param('page');
        $goods_list = Db::name('goods_mall')->where(['is_shelf'=>2])->page($page,2)->select();
        $goods_class = Db::name('goods_class')->select();
        $arr = array_count_values(array_column($goods_list,'parent_id'));
        foreach ($goods_class as $k=>$v){
            if (isset($arr[$v['id']])){
                $goods_class[$k]['count'] = $arr[$v['id']];
            }else{
                $goods_class[$k]['count'] = 0;
            }
        }
        $res['goods'] = $goods_list;
        $res['goods_class'] = $goods_class;
        $res['all'] = array_sum(array_column($goods_class,'count'));
        return ReturnMsg(1,'',$res);
    }

    public function Map(){

        return $this->fetch('Map');
    }
}